package cn.iocoder.yudao.module.brokerage.merchant.service;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.business.basic.dao.query.CoreQueryWrapper;
import cn.iocoder.yudao.framework.business.basic.service.impl.BaseService;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.module.brokerage.merchant.dao.BrokerageMerchantRecordMapper;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.po.AgencyBrokerageRecordDO;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.vo.AppBrokerageMerchantRecordQueryDTO;
import cn.iocoder.yudao.module.brokerage.merchant.pojo.vo.AppBrokerageMerchantRecordVO;
import jakarta.annotation.Nonnull;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 分佣记录 Service 实现类
 *
 * @author 山野羡民
 */
@Slf4j
@Service
@Validated
public class AppBrokerageMerchantRecordServiceImpl extends BaseService<AgencyBrokerageRecordDO, AppBrokerageMerchantRecordVO, AppBrokerageMerchantRecordQueryDTO> implements AppBrokerageMerchantRecordService {
    @Resource
    private BrokerageMerchantRecordMapper brokerageMerchantRecordMapper;

    @Override
    protected BrokerageMerchantRecordMapper getInjectedMapper() {
        return brokerageMerchantRecordMapper;
    }

    @Nonnull
    @Override
    protected CoreQueryWrapper<AgencyBrokerageRecordDO> buildQueryWrapper(AppBrokerageMerchantRecordQueryDTO param) {
        buildUnfreezeTime(param);
        CoreQueryWrapper<AgencyBrokerageRecordDO> wrapper = super.buildQueryWrapper(param);
        wrapper.eqIfPresent("status", param.getStatus());
        wrapper.eqIfPresent("trade_no", param.getTradeNo());
        wrapper.betweenIfPresent("unfreeze_time", param.getUnfreezeTime());
        wrapper.orderByDesc("id");
        return wrapper;
    }

    @Override
    public Integer getNumberSum(Long userId, AppBrokerageMerchantRecordQueryDTO param) {
        buildUnfreezeTime(param);
        return getInjectedMapper().selectNumberSum(userId, param);
    }

    private void buildUnfreezeTime(AppBrokerageMerchantRecordQueryDTO param) {
        Integer year = param.getYear();
        Integer month = param.getMonth();
        Integer day = param.getDay();
        if (year != null && year > 0 && month != null && month > 0) {
            if (day != null && day >= 0) {
                LocalDateTime startTime = LocalDateTimeUtil.beginOfDay(LocalDate.of(year, month, day));
                param.setUnfreezeTime(new LocalDateTime[]{startTime, startTime.plusDays(1)});
            } else {
                LocalDateTime startTime = LocalDateTimeUtils.beginOfMonth(LocalDateTimeUtil.beginOfDay(LocalDate.of(year, month, 1)));
                param.setUnfreezeTime(new LocalDateTime[]{startTime, startTime.plusMonths(1)});
            }
        }
    }

}